package com.ruoyi.web.controller.book;

import com.ruoyi.book.domain.BookInfo;
import com.ruoyi.book.domain.BorrowInfo;
import com.ruoyi.book.domain.ReaderInfo;
import com.ruoyi.book.service.IBookInfoService;
import com.ruoyi.book.service.IBorrowInfoService;
import com.ruoyi.book.service.IReaderInfoService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MailUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 借阅信息Controller
 * @author wcm
 * @date 2022-03-31
 */
@RestController
@RequestMapping("/borrow/info")
public class BorrowInfoController extends BaseController {
    @Autowired
    private IBorrowInfoService borrowInfoService;
    @Resource
    MailUtil mailUtil;
    @Resource
    private IBookInfoService bookInfoService;
    @Resource
    private IReaderInfoService readerInfoService;

    /**
     * 查询借阅信息列表
     */
    @PreAuthorize("@ss.hasPermi('borrow:info:list')")
    @GetMapping("/list")
    public TableDataInfo list(BorrowInfo borrowInfo) {
        startPage();
        List<BorrowInfo> list = borrowInfoService.selectBorrowInfoList(borrowInfo);
        // 获取当前时间
        LocalDate nowDay = LocalDate.now();
        for (BorrowInfo info : list) {
            LocalDate localEndDate = getLocalDateTimeFormDate(info.getBorrowEndTime()).toLocalDate();
            if ("1".equals(info.getState()) && nowDay.isAfter(localEndDate)) {
                info.setState("4");
                Date newDate = new Date();
                int overDay = Math.abs((int) ((newDate.getTime() - info.getBorrowEndTime().getTime()) / (1000 * 3600 * 24)));
                info.setOverdueDays(overDay);
                info.setOverdueAmount(overDay * info.getRent() * 2);
                borrowInfoService.updateBorrowInfo(info);
            }
        }
        return getDataTable(list);
    }

    public LocalDateTime getLocalDateTimeFormDate(Date date) {
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zone);
    }

    /**
     * 导出借阅信息列表
     */
    @PreAuthorize("@ss.hasPermi('borrow:info:export')")
    @Log(title = "借阅信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BorrowInfo borrowInfo) {
        List<BorrowInfo> list = borrowInfoService.selectBorrowInfoList(borrowInfo);
        ExcelUtil<BorrowInfo> util = new ExcelUtil<BorrowInfo>(BorrowInfo.class);
        util.exportExcel(response, list, "借阅信息数据");
    }

    /**
     * 获取借阅信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('borrow:info:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(borrowInfoService.selectBorrowInfoById(id));
    }

    /**
     * 新增借阅信息
     */
    @PreAuthorize("@ss.hasPermi('borrow:info:add')")
    @Log(title = "借阅信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BorrowInfo borrowInfo) {
        BookInfo bookInfo = bookInfoService.selectBookInfoById(borrowInfo.getBookId());
        ReaderInfo readerInfo = readerInfoService.selectReaderInfoById(borrowInfo.getReaderId());
        String subject = "借阅图书";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String startdateString = formatter.format(borrowInfo.getBorrowStartTime());
        String enddateString = formatter.format(borrowInfo.getBorrowEndTime());
        String content = "你已借阅《" + bookInfo.getBookName() + "》，借阅时间是" + startdateString + "到"+ enddateString+",请按时归还";
        String msg = mailUtil.sendSimpleMail(readerInfo.getEmail(), subject, content);

        bookInfo.setUnshelve(bookInfo.getUnshelve()-1);
        bookInfoService.updateBookInfo(bookInfo);
        return toAjax(borrowInfoService.insertBorrowInfo(borrowInfo));
    }

    /**
     * 修改借阅信息
     */
    @PreAuthorize("@ss.hasPermi('borrow:info:edit')")
    @Log(title = "借阅信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BorrowInfo borrowInfo) {
        if ("2".equals(borrowInfo.getState())) {
            borrowInfo.setReturnTime(new Date());
            BookInfo bookInfo = bookInfoService.selectBookInfoById(borrowInfo.getBookId());
            ReaderInfo readerInfo = readerInfoService.selectReaderInfoById(borrowInfo.getReaderId());
            String subject = "归还图书";
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = formatter.format(borrowInfo.getReturnTime());
            String content = "你借阅的《" + bookInfo.getBookName() + "》已成功归还，归还时间是" + dateString + ",欢迎下次光顾";
            String msg = mailUtil.sendSimpleMail(readerInfo.getEmail(), subject, content);
            bookInfo.setUnshelve(bookInfo.getUnshelve()+1);
            bookInfoService.updateBookInfo(bookInfo);
        }
        return toAjax(borrowInfoService.updateBorrowInfo(borrowInfo));
    }

    /**
     * 删除借阅信息
     */
    @PreAuthorize("@ss.hasPermi('borrow:info:remove')")
    @Log(title = "借阅信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(borrowInfoService.deleteBorrowInfoByIds(ids));
    }

    @GetMapping(value = "overDay/{id}")
    public AjaxResult getOverDay(@PathVariable("id") String id) {
        BorrowInfo borrowInfo = borrowInfoService.selectBorrowInfoById(id);
        Date newDate = new Date();
        int overDay = Math.abs((int) ((newDate.getTime() - borrowInfo.getBorrowEndTime().getTime()) / (1000 * 3600 * 24)));
        borrowInfo.setOverdueDays(overDay);
        borrowInfo.setOverdueAmount(overDay * borrowInfo.getRent() * 2);
        int row = borrowInfoService.updateBorrowInfo(borrowInfo);
        return AjaxResult.success(borrowInfo);
    }

    /**
     * @return
     * @Date 2022/4/9 16:26
     * @Author wcm
     * @Description //TODO 发送邮件
     **/
    @GetMapping("remind/{id}")
    public AjaxResult sendMail(@PathVariable("id") String id) {
        BorrowInfo borrowInfo = borrowInfoService.selectBorrowInfoById(id);
        BookInfo bookInfo = bookInfoService.selectBookInfoById(borrowInfo.getBookId());
        ReaderInfo readerInfo = readerInfoService.selectReaderInfoById(borrowInfo.getReaderId());
        String subject = "图书归还提醒";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(borrowInfo.getBorrowEndTime());
        String content = "你借阅的《" + bookInfo.getBookName() + "》借阅截止时间是" + dateString + ",即将超期,请及时归还，否则将支付超期金额";
        String msg = mailUtil.sendSimpleMail(readerInfo.getEmail(), subject, content);
        return AjaxResult.success(msg);
    }

}
